import { defineStore } from 'pinia';
import { ref } from 'vue';
import { API_CONFIG } from '../config/apiConfig';
import { InventoryItem, CreateInventoryItemRequest } from '../types/inventory';
import router from '../router';

// 创建统一的会话过期处理方法
function handleSessionExpired() {
  // 清理用户数据
  localStorage.removeItem('userInfo');
  document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  
  // 使用 replace 而不是 push 来防止用户通过浏览器后退返回
  router.replace('/');
}

// 响应模型
interface ResponseModel<T> {
  code: string | number;
  msg: string;
  data?: T;
}

// 分页响应类型
interface PageRsp<T> {
  pageNo: string | number;
  pageSize: string | number;
  total: string | number;
  dataList: T[];
}

export const useInventoryStore = defineStore('inventory', () => {
  // 状态
  const inventoryItems = ref<InventoryItem[]>([]);
  const isLoading = ref(false);
  const selectedLabId = ref<string | null>(null);
  const selectedType = ref<number | undefined>(undefined);
  const searchName = ref<string>(''); // 添加搜索关键词状态
  
  // 分页相关状态
  const pageNo = ref(1);
  const pageSize = ref(20);
  const total = ref(0);
  const hasMore = ref(true);
  const loadingMore = ref(false);

  // 设置选中的实验室ID
  const setSelectedLabId = (labId: string) => {
    selectedLabId.value = labId;
  };

  // 获取库存列表
  const fetchInventoryItems = async (labId: string, reset: boolean = true, type?: number, name?: string, filters?: Record<string, string>) => {
    if (reset) {
      pageNo.value = 1;
      inventoryItems.value = [];
      hasMore.value = true;
    }
    
    // 保存当前选中的类型和搜索关键词，用于加载更多时使用
    selectedType.value = type;
    if (name !== undefined) {
      searchName.value = name;
    }
    
    if (!hasMore.value) return true;
    
    isLoading.value = true;
    try {
      let url = `${API_CONFIG.BASE_URL}/inventory/page?pageNo=${pageNo.value}&pageSize=${pageSize.value}&researchGroupId=${labId}`;
      // 只有当type有值且不是-1时，才添加type参数
      if (type !== undefined && type >= 0) {
        url += `&type=${type}`;
      }
      
      // 如果有搜索关键词，添加name参数
      if (searchName.value) {
        url += `&name=${encodeURIComponent(searchName.value)}`;
      }
      
      // 添加其他搜索条件
      if (filters) {
        Object.entries(filters).forEach(([key, value]) => {
          if (value && key !== 'name') { // 避免重复添加name参数
            url += `&${key}=${encodeURIComponent(value)}`;
          }
        });
      }

      const response = await fetch(
        url,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include'
        }
      );

      const result: ResponseModel<PageRsp<InventoryItem>> = await response.json();
      
      if (result.code === 0 || result.code === '0') {
        if (result.data) {
          const { dataList, total: totalCount } = result.data;
          
          // 更新总数
          total.value = Number(totalCount);
          
          if (reset) {
            inventoryItems.value = dataList;
          } else {
            inventoryItems.value = [...inventoryItems.value, ...dataList];
          }
          
          // 检查是否还有更多数据
          hasMore.value = inventoryItems.value.length < total.value;
          
          return true;
        }
      } else if(result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return false;
      }
       else {
        console.error('获取库存列表失败:', result.msg);
        return false;
      }
    } catch (error) {
      console.error('获取库存列表请求失败:', error);
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 加载更多库存项
  const loadMoreInventoryItems = async (filters?: Record<string, string>) => {
    if (loadingMore.value || !hasMore.value || !selectedLabId.value) return;
    
    loadingMore.value = true;
    try {
      pageNo.value++;
      // 使用保存的类型值和搜索关键词，确保与当前筛选条件一致
      console.log(`加载更多，使用类型: ${selectedType.value === -1 ? '全部' : selectedType.value}, 搜索关键词: ${searchName.value || '无'}`);
      await fetchInventoryItems(selectedLabId.value, false, selectedType.value, searchName.value, filters);
    } finally {
      loadingMore.value = false;
    }
  };

  // 删除库存项
  const deleteInventoryItem = async (item: InventoryItem): Promise<{ success: boolean; message?: string }> => {
    if (!selectedLabId.value) {
      return { success: false, message: '请先选择一个实验室' };
    }
    
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/inventory/sku/${item.id}/${selectedLabId.value}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include'
      });

      const result = await response.json();
    
      if (result.code === 0 || result.code === '0') {
        // 删除成功后从本地列表中移除
        inventoryItems.value = inventoryItems.value.filter(i => i.id !== item.id);
        
        // 如果存在选中的实验室，刷新库存列表
        if (selectedLabId.value) {
          await fetchInventoryItems(selectedLabId.value, true);
        }
        
        return { success: true };
      } else if (result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return { success: false, message: '会话已过期，请重新登录' };
      } else {
        return { success: false, message: result.msg };
      }
    } catch (error) {
      console.error('删除请求失败:', error);
      return { success: false, message: '删除失败，请检查网络连接' };
    }
  };

  // 添加新库存项
  const addInventoryItem = async (data: CreateInventoryItemRequest): Promise<{ success: boolean; message?: string }> => {
    if (!selectedLabId.value) {
      return { success: false, message: '请先选择一个实验室' };
    }
  
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/inventory/sku`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
          ...data,
          researchGroupId: selectedLabId.value,
          // 确保日期格式正确，如果没有时间部分则添加
          expirationDate: data.expirationDate ? data.expirationDate : undefined
        })
      });

      const result = await response.json();
    
      if (result.code === 0 || result.code === '0') {
        // 重新加载库存数据
        if (selectedLabId.value) {
          await fetchInventoryItems(selectedLabId.value, true);
        }
        return { success: true };
      } else if (result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return { success: false, message: '会话已过期，请重新登录' };
      } else {
        return { success: false, message: result.msg };
      }
    } catch (error) {
      console.error('新增库存项请求失败:', error);
      return { success: false, message: '新增库存项失败，请检查网络连接' };
    }
  };

  // 初始化库存
  const initializeInventory = async (labId: string, formData?: FormData): Promise<{ success: boolean; message?: string }> => {
    try {
      // 确保formData存在，否则创建一个空的FormData
      const dataToSend = formData || new FormData();
      
      // 如果没有提供formData，则可能是简单初始化，需要添加researchGroupId
      if (!formData) {
        dataToSend.append('researchGroupId', labId);
      }
      
      const response = await fetch(`${API_CONFIG.BASE_URL}/inventory/init`, {
        method: 'POST',
        body: dataToSend,
        credentials: 'include'
      });

      const result = await response.json();
    
      if (result.code === 0 || result.code === '0') {
        // 重新加载库存数据
        await fetchInventoryItems(labId, true);
        return { success: true };
      } else if (result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return { success: false, message: '会话已过期，请重新登录' };
      } else {
        return { success: false, message: result.msg };
      }
    } catch (error) {
      console.error('初始化库存失败:', error);
      return { success: false, message: '初始化库存失败，请检查网络连接' };
    }
  };

  // 处理库存更新（入库/出库）
  const updateInventory = async (itemId: string, num: number, operationType: number): Promise<{ success: boolean; message?: string }> => {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/inventory/sku/${itemId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({ 
          operationType, // 0入库，1出库
          num 
        })
      });

      const result = await response.json();
    
      if (result.code === 0 || result.code === '0') {
        // 重新加载库存数据
        if (selectedLabId.value) {
          await fetchInventoryItems(selectedLabId.value, true);
        }
        return { success: true };
      } else if (result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return { success: false, message: '会话已过期，请重新登录' };
      } else {
        return { success: false, message: result.msg };
      }
    } catch (error) {
      console.error('库存更新操作失败:', error);
      return { success: false, message: '库存更新失败，请检查网络连接' };
    }
  };

  return {
    // 状态
    inventoryItems,
    isLoading,
    selectedLabId,
    selectedType,
    searchName,
    pageNo,
    pageSize,
    total,
    hasMore,
    loadingMore,
  
    // 方法
    setSelectedLabId,
    fetchInventoryItems,
    loadMoreInventoryItems,
    deleteInventoryItem,
    addInventoryItem,
    initializeInventory,
    updateInventory,
    handleOutbound: (itemId: string, num: number) => updateInventory(itemId, num, 1) // 保留旧方法以兼容现有代码
  };
});